<?php

namespace App\Task;

use App\Model\Applet;
use App\Model\DataUserClueToken;
use App\Model\Payment;
//use App\Model\Payment;
use App\Model\Playlet;
use App\Model\PlayletEpisodes;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;

//#[Crontab(name: "RedisTokenTask", rule: "*/5 * * * * *", callback: "execute", memo: "redis上所有的user token 存入数据表中'")]
class RedisTokenTask
{
    protected LoggerInterface $logger;
    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'redisToken');
    }
    public function execute()
    {
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------定时获取订单数据');
        $this->logger->info('开始获取订单未处理的数据');
        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('wx');
        $this->logger->info('获取所有拥有的微信的小程序');
        $appletData = Applet::query()->where(['type' => 1])->select(['id'])->get();
        if($appletData->isNotEmpty()){
            foreach ($appletData as $appletDatum) {
                $applet_id = $appletDatum->id;
                $redisKey = 'user_msg:'.$applet_id;
                $testSetKey = 'check_msg:'.$applet_id;
                $this->logger->info('查询这个小程序的用户redis', [$redisKey]);
                $redisCount = $redis->lLen($redisKey);

                //判断是否有值，有值取值出来遍历
                if($redisCount > 0){
                    $this->logger->info('小程序的用户redis总数', [$redisCount]);
                    for ($i=0;$i < $redisCount;$i++){
                        $redisInfo  = $redis->lPop($redisKey);
                        $redis->lPush($testSetKey,$redisInfo);

                        $redisRes = json_decode($redisInfo,true);
                        $this->logger->info('查询这个小程序的用户redis', [$redisRes]);
                        if(!empty($redisRes['query'])){
                            $queryInfo =  json_decode($redisRes['query'],true);
                            if(!empty($queryInfo['promotion_id'])){

                                Db::table('user_juliang_token_'.$applet_id)->insert(
                                    [
                                        'xc_open_id'    => $redisRes['xc_open_id'] ?? 0,
                                        'room_id'       => $quryInfo['room_id'] ?? 0,
                                        'promotion_id'  => $queryInfo['promotion_id'] ?? 0,
                                        'req_id'        => $queryInfo['req_id'] ?? 0,
                                        'clue_id'       => $queryInfo['clue_id'] ?? 0,
                                        'clickid'       => $queryInfo['clickid'] ?? 0,
                                        'peid'          => $queryInfo['peid'] ?? 0,
                                        'item_id'       => $queryInfo['item_id'] ?? 0,
                                        'advertiser_id' => $queryInfo['advertiser_id'] ?? 0,
                                        'mid1'          => $queryInfo['mid1'] ?? 0,
                                        'mid4'          => $queryInfo['mid4'] ?? 0,
                                        'aid'           => $queryInfo['aid'] ?? 0,
                                        'adv_id'        => $queryInfo['adv_id'] ?? 0,
                                        'mid5'          => $queryInfo['mid5'] ?? 0,
                                        'clue_token'    => $queryInfo['clue_token'] ?? 0,
                                        'mid3'          => $queryInfo['mid3'] ?? 0,
                                        'project_id'    => $queryInfo['project_id'] ?? 0,
                                        'pid'           => $queryInfo['pid'] ?? 0,
                                        'spread_id'     => $queryInfo['spread_id'] ?? 0,
                                        'mid2'          => $queryInfo['mid2'] ?? 0,
                                        'path'          => $redisRes['path'] ?? 0,
                                        'scene'         => $redisRes['scene'] ?? 0,
                                        'referrerInfo'  => $redisRes['referrerInfo'] ?? 0,
                                        'mode'          => $redisRes['mode'] ?? 0,
                                        'apiCategory'   => $redisRes['apiCategory'] ?? 0,
                                        'ut'            => $queryInfo['ut'] ?? 1,
                                        'created_at'    => date('Y-m-d H:i:s',time())
                                        ]
                                );
                            }
                                //假设 用user主表
                                //假设 用token
                                //时间， 修改用户时间 现在往前半小时
                                //有订单，
                                //插入token
                                //用户ad_id 判断这个用户是否又下订单，48小时之内如果又，那就不更新ad_id,跳出，48小时之后， ad_id 之前的
                                //1 de ad_id 保存着，有订单， 2的ad_id 不会更新，然后有新丁，1的ad_id 回传，除非说48小时h之后，有新的ad_id 我就更新。
                        }
                    }


//                    $this->logger->info('查询这个小程序的用户redis 测试的token', [$redis->lRange($testSetKey,0,-1)]);
                }
            }
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取订单进行上报');
    }
    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method,string $access_token = null)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        if(!empty($access_token)){
            $headers['access-token'] = $access_token;
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}